package com.epam.manager.backingbeans;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.enterprise.event.Event;
import javax.faces.model.DataModel;
import javax.inject.Inject;
import javax.transaction.UserTransaction;

import org.apache.log4j.Logger;

import com.epam.DAO.BillDAO;
import com.epam.DAO.CarDAO;
import com.epam.entity.Bill;
import com.epam.entity.Car;
import com.epam.entity.Request;
import com.epam.entity.Status;
import com.epam.events.Notifications;
import com.epam.events.TypedAnnotationLiteral;

public class NewRequestManagedBean extends RequestController {

	@EJB
	private BillDAO billDAO;
	@EJB
	private CarDAO carDAO;
	@Inject
	private Event<Request> eventProcessor;
	@Resource
	private UserTransaction ut;
	private Logger logger = Logger.getLogger(NewRequestManagedBean.class);
	private Request request = new Request();

	@Override
	public DataModel<Request> getRequests() {
		requests.setWrappedData(requestDAO.getRequests(firstRow, rowsPerPage,
				Status.NEW));
		totalRows = requestDAO.getRequestsCount(Status.NEW);
		// Set currentPage, totalPages and pages.
		currentPage = (totalRows / rowsPerPage)
				- ((totalRows - firstRow) / rowsPerPage) + 1;
		totalPages = (totalRows / rowsPerPage)
				+ ((totalRows % rowsPerPage != 0) ? 1 : 0);

		return requests;
	}

	public Request getRequest() {
		return request;
	}

	public void setRequest(Request request) {
		this.request = request;
	}

	public void initRequest() {
		request = requests.getRowData();
	}

	public void cancelRequest() {
		try {
			try {
				ut.begin();

				request.setStatus(Status.CANCELLED);
				requestDAO.update(request);

				Car car = request.getCar();
				car.setIsAvaliable(true);
				carDAO.update(car);

				eventProcessor.fire(request);

				eventProcessor.select(
						new TypedAnnotationLiteral(Notifications.CANCELLED))
						.fire(request);

				ut.commit();
			} catch (Exception e) {
				ut.rollback();
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}

	}

	public void approveRequest() {
		try {
			try {
				ut.begin();
				request.setStatus(Status.APPROVED);

				long days = (request.getEndDate().getTime() - request
						.getBeginDate().getTime()) / (1000 * 60 * 60 * 24);

				double sum = request.getCar().getRentRate() * days;
				sum *= 100;
				sum = (double) Math.round(sum) / 100;

				Bill bill = new Bill(request, sum, Status.NOT_PAYED,
						"RENT PAYMENT");
				billDAO.create(bill);

				eventProcessor.select(
						new TypedAnnotationLiteral(Notifications.APPROVED))
						.fire(request);

				requestDAO.update(request);
				ut.commit();
			} catch (Exception e) {
				ut.rollback();
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}
	}

}
